package cn.itcast.bos.web.action.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.service.system.RoleService;
import cn.itcast.bos.web.action.common.BaseAction;

@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("struts-default")
@Results({ @Result(name = "list", type = "redirect", location = "/pages/system/role.jsp"),
		@Result(name = "edit", location = "/pages/system/role_edit.jsp")
})
public class RoleAction extends BaseAction<Role> {
	//依赖注入
	@Autowired
	private RoleService roleService;


	//模型驱动 从页面上获取的菜单id，字符串，用逗号隔开
	private String menuIds;
	private Integer[] permissionIds;
	public void setMenuIds(String menuIds) {
		this.menuIds = menuIds;
	}
	public void setPermissionIds(Integer[] permissionIds) {
		this.permissionIds = permissionIds;
	}

	
	
	
	//页面异步加载所有角色
	@Action("roleAction_findAll")
	public String findAll() {
		List<Role> list = roleService.findAll();
		java2Json(list, new String[] { "users", "permissions", "menus" });
		return NONE;
	}
	@Action("roleAction_save")
	public String save() throws Exception{
		if(model.getId()!=null){
			roleService.update(model,menuIds,permissionIds);
		}else{
			roleService.save(model,menuIds,permissionIds);
		}
		return "list";
	}

	@Action("roleAction_edit")
	public String toEdit(){
		model=roleService.findById(model.getId());
		return "edit";
	}
	
	@Action("roleAction_findPermissionByRoleId")
	public String findPermissionByRoleId(){
		List l=new ArrayList<String>();
		model=roleService.findById(model.getId());
		l.addAll(model.getPermissions());
		java2Json(l,new String[] { "roles" });
		return NONE;
	}
	@Action("roleAction_findMenuByRoleId")
	public String findMenuByRoleId(){
		List l=new ArrayList<String>();
		model=roleService.findById(model.getId());
		l.addAll(model.getMenus());
		java2Json(l, new String[] { "roles", "children", "childrenMenus" });
		return NONE;
	}
}
